package com.csu.soa_library.controller;

import com.csu.soa_library.common.CommonResponse;
import com.csu.soa_library.entity.Account;
import com.csu.soa_library.entity.Book;
import com.csu.soa_library.entity.User;
import com.csu.soa_library.service.UserService;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;
    private List<CommonResponse.Link> createLinks(int userId) {
        List<CommonResponse.Link> links = new ArrayList<>();

        links.add(new CommonResponse.Link("register", "http://localhost:8081/api/users/register", "POST"));
        links.add(new CommonResponse.Link("login", "http://localhost:8081/api/users/login", "POST"));
        links.add(new CommonResponse.Link("userInfo", "http://localhost:8081/api/users/" + userId, "GET"));
        links.add(new CommonResponse.Link("update-userInfo", "http://localhost:8081/api/users/" + userId, "PUT"));
        links.add(new CommonResponse.Link("deleteUser", "http://localhost:8081/api/users/" + userId, "DELETE"));

        return links;
    }

    private Object convertToJson(Account account) {
        return null;
    }
    private String convertToXml(Account account, List<CommonResponse.Link> links) {
        try {
            XmlMapper xmlMapper = new XmlMapper();
            CommonResponse.DataWrapper3<Account> dataWrapper = new CommonResponse.DataWrapper3<>(account, links);
            return xmlMapper.writeValueAsString(dataWrapper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @PostMapping("/register")
    public Object registerAccount(@RequestBody Account account, @RequestParam(defaultValue = "1") String format) {
        String logMsg = userService.registerAccount(account);
        List<CommonResponse.Link> links = createLinks(account.getAccountId());
        //根据 format 参数决定返回的响应格式
        if ("0".equals(format)) {
            // 返回 XML 格式的响应，这里需要你实现转换逻辑
            String xmlResponse = convertToXml(account, links);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        } else {
            // 默认返回 JSON 格式的响应
            CommonResponse<CommonResponse.Link> response = CommonResponse.createForSuccess(0,"注册成功", links);
            return response;
        }
    }
    @PostMapping("/login")
    public Object loginAccount(@RequestParam("username") String username,
                               @RequestParam("password") String password,
                               @RequestParam(defaultValue = "1") String format){
        Map<String, Object> response1 = new HashMap<>();
        response1= userService.logAccount(username,password);
        String logMsg = (String)response1.get("message");
        int accountId = (int)response1.get("userId");
        List<CommonResponse.Link> links = createLinks(accountId);
        if(logMsg.equals("success")){
            Account account=new Account();
            account.setUsername(username);
            account.setPassword(password);
            if ("0".equals(format)){
                String xmlResponse = convertToXml(account, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            }
            // 默认返回 JSON 格式的响应
            CommonResponse<CommonResponse.Link> response = CommonResponse.createForSuccess(0,"登录成功", links);
            return response;
        }
        if ("0".equals(format)){
            String xmlResponse = convertToXml(null, links);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        }
        return CommonResponse.createForError("登录失败", links);
    }
    @GetMapping("/{userId}")
    public Object getAccountInfo(@PathVariable("userId") int accountId, @RequestParam(defaultValue = "1") String format){
        Account account = userService.getAccountInfo(accountId);
        List<CommonResponse.Link> links = createLinks(accountId);
        if (account != null) {
            if ("0".equals(format)) {
                // 返回 XML 格式的响应，这里需要你实现转换逻辑
                String xmlResponse = convertToXml(account, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            } else {
                // 默认返回 JSON 格式的响应
                CommonResponse.DataWrapper3<Account> dataWrapper = new CommonResponse.DataWrapper3<>(account, links);
                CommonResponse<Account> response = CommonResponse.createForSuccess(0, "查询成功", dataWrapper);
                return response;
            }
        } else {
            if ("0".equals(format)){
                String xmlResponse = convertToXml(null, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            }
            return CommonResponse.createForError("查询失败", links);
        }
    }
    @PutMapping("/{userId}")
    public Object updateAccountInfo(@PathVariable("userId") int userId,@RequestBody Account account, @RequestParam(defaultValue = "1") String format){
        account.setAccountId(userId);
        System.out.println(userId);
        System.out.println(account);
        String logMsg = userService.updateAccountInfo(account);
        List<CommonResponse.Link> links = createLinks(account.getAccountId());
        System.out.println(logMsg);
        if (logMsg.equals("success")){
            if ("0".equals(format)) {
                // 返回 XML 格式的响应，这里需要你实现转换逻辑
                String xmlResponse = convertToXml(account, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            } else {
                // 默认返回 JSON 格式的响应
                CommonResponse.DataWrapper3<Account> dataWrapper = new CommonResponse.DataWrapper3<>(account, links);
                CommonResponse<Account> response = CommonResponse.createForSuccess(0, "更新成功", dataWrapper);
                return response;
            }
        } else {
            if ("0".equals(format)){
                String xmlResponse = convertToXml(null, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            }
            CommonResponse response = CommonResponse.createForError("更新失败", links);
            return response;
        }
    }
    @DeleteMapping("/{userId}")
    public Object deleteUser(@PathVariable("userId") int userId, @RequestParam(defaultValue = "1") String format){
        String logMsg = userService.deleteAccount(userId);
        List<CommonResponse.Link> links = createLinks(userId);
        System.out.println(logMsg);
        if(logMsg.equals("success")){
            if ("0".equals(format)){
                String xmlResponse = convertToXml(null, links);
                return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
            }
            // 默认返回 JSON 格式的响应
            CommonResponse<CommonResponse.Link> response = CommonResponse.createForSuccess(0,"删除成功", links);
            return response;
        }
        if ("0".equals(format)){
            String xmlResponse = convertToXml(null, links);
            return ResponseEntity.ok().contentType(MediaType.APPLICATION_XML).body(xmlResponse);
        }
        return CommonResponse.createForError("删除失败", links);
    }

}
